package com.factory.rest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.factory.common.pojo.Result;
import com.factory.common.pojo.SendData;
import com.factory.common.utils.StringUtil;
import com.factory.rest.feign.AiClients;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * webRTC-Streamer 控制类
 *
 * @author JW
 * @version 1.0
 * @date 2021/5/31 11:04
 */
@RestController
@RequestMapping("/rest/streamer")
@Slf4j
public class WebRTCStreamerController {

    @Autowired
    private AiClients aiClients;

    private String contentType = "text/plain;charset=UTF-8";

    @RequestMapping(value = "/{deviceId}/api/getIceServers", method = RequestMethod.GET)
    public void getIceServers(HttpServletResponse response, HttpServletRequest request, @PathVariable("deviceId") String deviceId) {
        log.info("/api/getIceServers,{}");

        if (StringUtil.notEmpty(deviceId)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url", "/api/getIceServers");
            jsonObject.put("contentType", contentType);
            jsonObject.put("requestMethod", "GET");
            Result result = aiClients.sendClient(new SendData(deviceId, StringUtil.getUUID(), "webRTC_streamer", jsonObject, true));
            response0(response, result);
        }
    }

    @RequestMapping(value = "/{deviceId}/api/call", method = RequestMethod.POST)
    public void call(HttpServletResponse response, @RequestBody String params, @PathVariable("deviceId") String deviceId, @RequestParam String peerid, @RequestParam String url) {
        log.info("/api/call,{}", params);
        if (StringUtil.notEmpty(deviceId)) {
            JSONObject jsonObject = new JSONObject();
//            http://192.168.8.114:8000/api/call?peerid=0.33126161528484066&url=rtsp%3A%2F%2Fadmin%3Aa1234567%40192.168.8.17%3A554%2Fh264%2Fch1%2Fmain%2Fav_stream
            jsonObject.put("url", String.format("/api/call?peerid=%s&url=%s", peerid, url));
            jsonObject.put("contentType", contentType);
            jsonObject.put("requestBody", params);
            jsonObject.put("requestMethod", "POST");
            Result result = aiClients.sendClient(new SendData(deviceId, StringUtil.getUUID(), "webRTC_streamer", jsonObject, true));
            response0(response, result);
        }
    }

    @RequestMapping(value = "/{deviceId}/api/addIceCandidate", method = RequestMethod.POST)
    public void addIceCandidate(HttpServletResponse response, @PathVariable("deviceId") String deviceId, @RequestBody String params, @RequestParam String peerid) {
        log.info("/api/addIceCandidate,{}", params);
        if (StringUtil.notEmpty(deviceId)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url", String.format("/api/addIceCandidate?peerid=%s", peerid));
            jsonObject.put("contentType", contentType);
            jsonObject.put("requestBody", params);
            jsonObject.put("requestMethod", "POST");
            Result result = aiClients.sendClient(new SendData(deviceId, StringUtil.getUUID(), "webRTC_streamer", jsonObject, true));
            response0(response, result);
        }
    }

    @RequestMapping(value = "/{deviceId}/api/getIceCandidate", method = RequestMethod.GET)
    public void getIceCandidate(HttpServletResponse response, @PathVariable("deviceId") String deviceId, @RequestParam String peerid) {
        log.info("/api/getIceCandidate");
        if (StringUtil.notEmpty(deviceId)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url", String.format("/api/getIceCandidate?peerid=%s", peerid));
            jsonObject.put("contentType", contentType);
            jsonObject.put("requestMethod", "GET");
            Result result = aiClients.sendClient(new SendData(deviceId, StringUtil.getUUID(), "webRTC_streamer", jsonObject, true));
            response0(response, result);
        }
    }

    @RequestMapping(value = "/{deviceId}/api/hangup", method = RequestMethod.GET)
    public void hangup(HttpServletResponse response, @PathVariable("deviceId") String deviceId, @RequestParam String peerid) {
        log.info("/api/hangup,{}");
        if (StringUtil.notEmpty(deviceId)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url", String.format("/api/hangup?peerid=%s", peerid));
            jsonObject.put("contentType", contentType);
            jsonObject.put("requestMethod", "GET");
            Result result = aiClients.sendClient(new SendData(deviceId, StringUtil.getUUID(), "webRTC_streamer", jsonObject, true));
            response0(response, result);
        }
    }

    private void response0(HttpServletResponse response, Result result) {
        if (result.isStatus()) {
            response.setContentType(contentType);
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                if (StringUtil.notEmpty(result.getData())) {
                    if (result.getData() instanceof String)
                        writer.print(result.getData().toString());
                    else
                        writer.print(JSON.toJSONString(result.getData()));
                }
                writer.flush();
            } catch (IOException e) {
                log.error("发生servlet错误,{}", e);
            } finally {
                if (null != writer) {
                    writer.close();
                }
            }
        } else
            log.error("发送aiclent微服务远程调用失败,{}", result.getMessage());
    }
}
